package asteroids.engine;

import java.awt.Graphics;
import java.util.ArrayList;

import org.apache.log4j.Logger;

import asteroids.entity.Ship;

public class ShipManager implements ObjectManager<Ship>
{
    private Logger logger = Logger.getLogger(ObjectManager.class);

    private ArrayList<Ship> ships;

    public ShipManager()
    {
        ships = new ArrayList<Ship>();
    }

    public void add(Ship obj)
    {
        ships.add(obj);
    }

    public void addAll(ArrayList<? extends Ship> all)
    {
        ships.addAll(all);
    }

    public ArrayList<Ship> getObjects()
    {
        return ships;
    }

    public void update()
    {
        logger.warn("Updating reasoning entities without a GameState");
        for( Ship s : ships )
        {
            s.update();
        }
    }

    public void update(GameState state)
    {
        /*
         * update in multiple phases to ensure that everything interacts and
         * renders properly: -Ship -Bullets -Equipment
         */
        for( int i = ships.size() - 1; i >= 0; i-- )
        {
            Ship s = ships.get(i);
            if( s.isActive() )
            {
                s.update(state);
            }
            else
            {
                s.destroy();
                ships.remove(s);
                s = null;
            }
        }
        for( Ship s : ships )
        {
            s.updateWeapons(state);
        }
        for( Ship s : ships )
        {
            s.updateEquipment(state);
        }
    }

    public void clear()
    {
        ships.clear();
    }

    public void draw(Graphics g)
    {
        for( Ship s : ships )
        {
            // if(s.isAlive()) // this check is done in GameObject now...
            // {
            s.draw(g);
            // }
        }
    }

    public void erase(Graphics g)
    {
        for( Ship s : ships )
        {
            s.erase(g);
        }
    }
}
